use hmac::{Hmac, NewMac};
use jwt::VerifyWithKey;
use jwt::{AlgorithmType, Header, SignWithKey, Token};
use sha2::Sha256;
use sha2::Sha384;
use std::collections::BTreeMap;


///生成token
#[test]
pub fn generate_token(){
    let key: Hmac<Sha256> = Hmac::new_from_slice(b"89sI9Ii8nJslx6Xw").unwrap();
    let mut claims = BTreeMap::new();
    claims.insert("username", "lisi");
    let token_str = claims.sign_with_key(&key).unwrap();
    println!("{}", token_str); //
}

/// 解析token
#[test]
pub fn parse_token(){
    let key: Hmac<Sha256> = Hmac::new_from_slice(b"89sI9Ii8nJslx6Xw").unwrap();
    let token = "eyJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6Imxpc2kifQ.oqiK7OTLUgPB0Ygb0uletqUqcAdFNiPIPN4maZhmOsk";
    let claims: BTreeMap<String, String> = token.verify_with_key(&key).unwrap();
    let username = &claims["username"];
    println!("{}", username); //lisi
}

///自定义Header
#[test]
pub fn header_generate_token(){
    let key: Hmac<Sha384> = Hmac::new_from_slice(b"89sI9Ii8nJslx6Xw").unwrap();
    //生成token
    let header = Header {
        algorithm: AlgorithmType::Hs384,
        ..Default::default()
    };
    let mut claims = BTreeMap::new();
    claims.insert("sub", "someone");
    let token = Token::new(header, claims).sign_with_key(&key).unwrap();
    let s = token.as_str();
    println!("{}", s); //eyJhbGciOiJIUzM4NCJ9.eyJzdWIiOiJzb21lb25lIn0.DG6S5c7N4b6lnlt0XuMflpWrNd54fM1ndsVI-2CSfB6ciaZA_1Nd7dZoCceAcn0_


    //解析token
    let token: Token<Header, BTreeMap<String, String>, _> = s.verify_with_key(&key).unwrap();
    let header = token.header();
    let claims = token.claims();
    println!("{:?}", header.algorithm); //Hs384
    println!("{:?}", claims); //{"sub": "someone"}

}